package com.vint.mi;

import java.util.HashMap;
import java.util.Map;

/**
 * 最长连续数列，要求O(n)复杂度, Leetcode:128
 */
public class Mi4 {
    public static String solution(String line){
        if(null==line||line.length()==0){
            return "0";
        }
        String[] src =  line.split(",");
        Map<Integer,Integer> indexMap = new HashMap<Integer, Integer>();
        Map<Integer,Boolean> visitMap = new HashMap<Integer, Boolean>();
        for(int i = 0; i < src.length; i++){
            visitMap.put(i,false);
            if(!indexMap.containsKey(Integer.parseInt(src[i]))){
                indexMap.put(Integer.parseInt(src[i]),i);
            }
        }
        int max = 0;
        for(int i = 0; i < src.length && !visitMap.get(i); i++){
            int length = 0;
            int sr = Integer.parseInt(src[i]);
            int j = 0;
            //没有访问
            while (indexMap.containsKey(sr+j)&&!visitMap.get(indexMap.get(sr+j))){
               length++;
                //这里容易错
               visitMap.put(indexMap.get(sr+j),true);
                j++;
            }
            j = 1;
            while (indexMap.containsKey(sr-j)&&!visitMap.get(indexMap.get(sr-j))){
                length++;
                //这里容易错
                visitMap.put(indexMap.get(sr-j),true);
                j++;
            }
            if(length>max){
                max = length;
            }
        }
        return max+"";
    }
    public static void main(String[] args) {
        String ex1 = "5,4,3,2,0,1";
        String ex2 = "-9,-4,9,-7,0,7,3,-1,6,2,-2,8,-2,0,2,-7,-5,-2,6,-5,0,-8,8,1,0,6,8,-8,-1";
        System.out.println(solution(ex1));
        System.out.println(solution(ex2));

    }
}
